<template>
  <div style="position: relative">
    <div id="container" ref="graphContainer" style="width: 100%; height: 80vh"></div>
    <configuringModelRelationships ref="config" />
  </div>
</template>
<script>
// import G6 from '@antv/g6'
import { Graph } from '@antv/x6'

import configuringModelRelationships from '../../configuringModelRelationships/index.vue'

import { metaModelfieldRelation, fieldRelation, queryRelation } from '@/api/metadata/label/metadataLabel.js'
export default {
  props: ['listArrrayTo'],
  components: {
    configuringModelRelationships,
  },
  data() {
    return {
      dataArrChildite: [],
      closeWacth: true,
      list: [],
      data: [],
      graph: null,
      edgetype: '',
      edgelist: [],

      ruletList: {},
      source: {
        x: '',
        y: '',
      },
      target: {
        x: '',
        y: '',
      },
      ruleForm: {},
      removeBtn: {
        sourceX: '',
        sourceY: '',
        targetX: '',
        targetY: '',
        sourceData: {},
        targetData: {},
      },
      name: '',
      item: {},
      incidenceRelation: '',
      graphId: '',
      graphId2: '',
      type: '',
      x6List: {
        cellList: [],
        edgeList: [],
      },
      type: '',
      modelId: '',
      metaModelFieldRelationEntities: [],
    }
  },
  watch: {
    listArrrayTo: {
      handler: function (newarr, oldarr) {
        console.log(newarr[0], oldarr[0], '000000000000')
        console.log(newarr, 'WACTH  过来了吗')

        const exists = this.x6List.cellList.some((item) => item.tableId === newarr[0].tableId)
        if (!exists) {
          this.x6List.cellList.push(...newarr)

          this.addNewNode(newarr[0])
        } else {
          this.$message({
            showClose: true,
            message: '表已存在画布中,不可重复添加!',
            type: 'warning',
          })
        }
        this.getG6Echarts()
      },
      // deep: true
      // immediate: true
    },
  },
  created() { },
  mounted() {
    this.type = this.$route.query.type
    this.modelId = this.$route.query.modelId
    if (this.type == 'add') {
      this.x6List.cellList = []
      this.x6List.edgeList = []
      this.getG6Echarts()
    } else if (this.type == 'edit') {
      fieldRelation({ modelId: this.modelId }).then((res) => {
        this.x6List = res.data.rows[0].x6List[0]
        this.metaModelFieldRelationEntities = res.data.rows[0].metaModelFieldRelationEntities
        console.log(this.x6List, 'mounted')
        this.getG6Echarts()
      })
    }
  },
  methods: {
    addNewNode(newarr) {
      // 创建新节点的数据
      // const newNodeData = {
      //   id: newarr.id,
      //   shape: 'rect',
      //   x: newarr.x,
      //   y: newarr.y,
      //   width: 300,
      //   height: 60,
      //   label: newarr.label
      // }

      const newNodeData = {
        x: newarr.x,
        y: newarr.y,
        width: 300,
        height: 60,
        shape: 'custom-node',

        data: {
          tableId: newarr.tableId,
          tableName: newarr.tableName,
        },
        attrs: {
          image: {
            opacity: 0.7,

            'xlink:href': '../../../../../../assets/images/数据库.webp',
          },
          title: {
            text: newarr.tableName,
            fontSize: 13,
            fontFamily: 'Arial',

            letterSpacing: 0,
          },
          text: {
            text: newarr.tableDescription ? newarr.tableDescription : '',
            fontSize: 13,
            fontFamily: 'Arial',

            letterSpacing: 0,
          },
        },
        tools: [
          {
            name: 'button-remove',
            args: {
              distance: -40,
              onClick: (view) => {
                console.log(view, '--->removeItemadd')
                const item = view.cell
                this.graph.removeNode(item.id)
                this.removeItem(item)
              },
            },
          },
        ],
        ports: {
          groups: {
            // 输入链接桩群组定义
            in: {
              position: 'top',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff',
                },
              },
            },
            // 输出链接桩群组定义
            out: {
              position: 'bottom',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff',
                },
              },
            },
            topLeft: {
              position: 'left',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff',
                },
              },
            },
            bottomRight: {
              position: 'right',
              attrs: {
                circle: {
                  r: 6,
                  magnet: true,
                  stroke: '#31d0c6',
                  strokeWidth: 2,
                  fill: '#fff',
                },
              },
            },
          },
          items: [
            {
              id: 'port1',
              group: 'in',
            },
            {
              id: 'port2',
              group: 'in',
            },
            {
              id: 'port3',
              group: 'out',
            },
            {
              id: 'port4',
              group: 'out',
            },
            {
              id: 'port5',
              group: 'topLeft',
            },
            {
              id: 'port6',
              group: 'bottomRight',
            },
          ],
        },
      }

      const newNode = this.graph.createNode(newNodeData)
      this.graph.addNode(newNode)
    },
    getG6Echarts() {
      if (this.graph) {
        this.graph.dispose()
      }
      console.log('第一步')
      const magnetAvailabilityHighlighter = {
        name: 'stroke',
        args: {
          padding: 3,
          attrs: {
            strokeWidth: 3,
            stroke: '#52c41a',
          },
        },
      }
      const container = this.$refs.graphContainer

      Graph.registerNode(
        'custom-node',
        {
          width: 300,
          height: 60,
          attrs: {
            body: {
              stroke: '#5F95FF',
              strokeWidth: 1,
              fill: '#ffffff',
              refWidth: 1,
              refHeight: 1,
            },
            image: {
              width: 36,
              height: 36,
              x: 12,
              y: 12,
            },
            title: {
              refX: 55,
              refY: 14,
              fill: 'rgba(0,0,0,0.85)',
              fontSize: 12,
              'text-anchor': 'start',
            },
            text: {
              refX: 55,
              refY: 38,
              fontSize: 12,
              fill: 'rgba(0,0,0,0.6)',
              'text-anchor': 'start',
            },
          },
          markup: [
            {
              tagName: 'rect',
              selector: 'body',
            },
            {
              tagName: 'image',
              selector: 'image',
            },
            {
              tagName: 'text',
              selector: 'title',
            },
            {
              tagName: 'text',
              selector: 'text',
            },
          ],
        },
        true
      )

      this.graph = new Graph({
        container,
        panning: true,
        highlighting: {
          magnetAvailable: magnetAvailabilityHighlighter,
        },
        connecting: {
          snap: true,
          allowBlank: false,
          allowLoop: false,
          allowNode: false,
          highlight: true,
        },
      })

      this.graph.on('edge:connected', ({ edge, previous, current }) => {
        console.log(edge, 'edgeedgeedgeedgeedgeedge')
        this.graphId = edge.id

        const sourceNode = edge.getSourceNode()
        const targetNode = edge.getTargetNode()
        console.log(sourceNode, targetNode, '7777')
        const sourceData = sourceNode.getData()
        const targetData = targetNode.getData()
        edge.setLabels([
          {
            attrs: {
              text: {
                text: '请输入表关系',
              },
            },
          },
        ])
        if (this.x6List.edgeList.length > 0) {
          let isLinked = false // 标记是否已经连线
          isLinked = this.x6List.edgeList.some((v) => {
            return (v.sourceId == sourceData.tableId || v.sourceId == targetData.tableId) && (v.targetId == sourceData.tableId || v.targetId == targetData.tableId)
          })

          if (isLinked) {
            console.log(this.x6List.edgeList, 'zenglema????')
            this.$message.warning('不可以重复连接')
            this.graph.removeEdge(this.graphId)
          } else {
            this.x6List.edgeList.push({
              sourceCell: '',
              targetCell: '',
              graphId: this.graphId,
              sourceId: sourceData.tableId,
              sourceName: sourceData.tableName,
              sourcePort: edge.source.port,
              targetId: targetData.tableId,
              targetName: targetData.tableName,
              targetPort: edge.target.port,
            })
            this.$emit('sourceortarge', [sourceData, targetData])

            console.log(this.x6List.edgeList, '里面的else')
          }
        } else {
          this.x6List.edgeList.push({
            sourceCell: '',
            targetCell: '',
            graphId: this.graphId,
            sourceId: sourceData.tableId,
            sourceName: sourceData.tableName,
            sourcePort: edge.source.port,
            targetId: targetData.tableId,
            targetName: targetData.tableName,
            targetPort: edge.target.port,
          })
          this.$emit('sourceortarge', [sourceData, targetData])
          console.log('没连线,可以连线', this.x6List.edgeList)
        }
      })
      this.graph.on('edge:dblclick', ({ e, x, y, edge, view }) => {
        const currentLabel = edge.getLabelAt(0)
        console.log(currentLabel, 'abcabcabc')
        const sourceNode = edge.getSourceNode()
        const targetNode = edge.getTargetNode()
        console.log(sourceNode, targetNode, '7777')
        const sourceData = sourceNode.getData()
        const targetData = targetNode.getData()
        let title = ''
        if (currentLabel === undefined) {
          title = '请输入关联关系'
        } else {
          if (currentLabel.attrs.label) {
            title = currentLabel.attrs.label.text
          } else {
            title = currentLabel.attrs.text.text
          }
        }

        this.$prompt('请输入关联关系', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: title,
        })
          .then(({ value }) => {
            console.log(value, '输入的文字是什么')
            if (value) {
              edge.setLabelAt(0, {
                attrs: {
                  text: {
                    text: value,
                  },
                },
              })
              this.x6List.edgeList.forEach((item) => {
                if (item.sourceId == sourceData.tableId && item.targetId == targetData.tableId) {
                  item.edgeLabel = value
                }
              })
            } else {
            }
          })
          .catch((err) => {
            if (err == 'cancel') {
              this.$message({
                type: 'info',
                message: '取消输入',
              })
            } else {
              console.log(err, 'errerreerrrerrererer')
            }
          })

        console.log(this.x6List.edgeList, '看看新文本')
      })
      this.graph.on('edge:mouseenter', ({ cell }) => {
        const edgeId = cell.id
        const sourceNode = cell.getSourceNode()
        const targetNode = cell.getTargetNode()
        const sourceData = sourceNode.getData()
        const targetData = targetNode.getData()
        console.log('11111111111')
        // cell.addTools([
        //   {
        //     name: 'button-remove',
        //     args: {
        //       distance: 40,
        //       onClick: (args) => {
        //         console.log(args, '=========>')
        //         console.log(this.graph, '=========>')
        //         this.graph.removeEdge(edgeId)

        //         this.$refs.config.off()
        //         this.x6List.edgeList.map((v, i) => {
        //           if ((v.sourceId == sourceData.tableId || v.sourceId == targetData.tableId) && (v.targetId == sourceData.tableId || v.targetId == targetData.tableId)) {
        //             this.x6List.edgeList.splice(i, 1)
        //           } else {
        //           }
        //         })
        //         localStorage.removeItem('data')
        //         localStorage.removeItem('date')
        //       },
        //     },
        //   },
        // ])
      })

      this.graph.on('edge:contextmenu', ({ edge, e }) => {
        console.log(edge, '右键点击的edge')
        e.preventDefault() // 阻止默认的浏览器右键菜单

        const sourceNode = edge.getSourceNode()
        const targetNode = edge.getTargetNode()

        console.log('hello', sourceNode)
        console.log('bye', targetNode)
        this.$refs.config.open([sourceNode.data, targetNode.data])
        this.$refs.config.edgelisthix()
      })

      this.graph.on('node:moved', ({ e, x, y, node, view }) => {
        // console.log(
        //   e,
        //   '---',
        //   x,
        //   '----',
        //   y,
        //   '-----',
        //   node,
        //   '-------',
        //   view,
        //   'node移动'
        // )
        this.closeWacth = false
        this.x6List.cellList.map((item) => {
          if (item.tableId == node.data.tableId) {
            item.x = x
            item.y = y
          }
        })
        this.closeWacth = true
      })

      console.log('第第二步')
      const newCellList = []
      this.x6List.cellList.map((v, i) => {
        let x = v.x
        let y = v.y
        let numX = Number(x)
        let numY = Number(y)

        const newCell = this.graph.addNode({
          x: numX,
          y: numY,
          width: 300,
          height: 60,
          shape: 'custom-node',

          data: {
            tableId: v.tableId,
            tableName: v.tableName,
          },
          attrs: {
            image: {
              opacity: 0.7,
              'xlink:href': 'https://img0.baidu.com/it/u=1042886901,3501250760&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
            },
            title: {
              text: v.tableName,
              fontSize: 13,
              fontFamily: 'Arial',
              letterSpacing: 0,
            },
            text: {
              text: v.tableDescription ? v.tableDescription : '',
              fontSize: 13,
              fontFamily: 'Arial',
              letterSpacing: 0,
            },
          },
          tools: [
            {
              name: 'button-remove',
              args: {
                distance: -80,
                onClick: (view) => {
                  localStorage.removeItem('data')
                  localStorage.removeItem('date')
                  this.$refs.config.off()
                  // this.item = view.cell.animation.cell.store.data.data
                  // this.removeItem(this.item)
                  // this.listArrray.forEach((item, index) => {
                  //   if (item.id == this.item.id) {
                  //     this.listArrray.splice(index, 1)
                  //   }
                  // })
                  // //TODO
                  // this.getG6Echarts()

                  const item = view.cell
                  this.graph.removeNode(item.id)
                  this.removeItem(item)
                  // console.log(this.listArrray, 'remove List-->>')
                },
              },
            },
          ],
          ports: {
            groups: {
              // 输入链接桩群组定义
              in: {
                position: 'top',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff',
                  },
                },
              },
              // 输出链接桩群组定义
              out: {
                position: 'bottom',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff',
                  },
                },
              },
              topLeft: {
                position: 'left',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff',
                  },
                },
              },
              bottomRight: {
                position: 'right',
                attrs: {
                  circle: {
                    r: 6,
                    magnet: true,
                    stroke: '#31d0c6',
                    strokeWidth: 2,
                    fill: '#fff',
                  },
                },
              },
            },
            items: [
              {
                id: 'port1',
                group: 'in',
              },
              {
                id: 'port2',
                group: 'in',
              },
              {
                id: 'port3',
                group: 'out',
              },
              {
                id: 'port4',
                group: 'out',
              },
              {
                id: 'port5',
                group: 'topLeft',
              },
              {
                id: 'port6',
                group: 'bottomRight',
              },
            ],
          },
        })
        newCellList.push(newCell)
        console.log(newCellList, '~~~newCellListnewCellListnewCellList')
      })

      this.x6List.edgeList.forEach((item) => {
        newCellList.forEach((newCellItem) => {
          if (item.sourceId === newCellItem.data.tableId) {
            item.sourceCell = newCellItem.id
          }

          if (item.targetId === newCellItem.data.tableId) {
            item.targetCell = newCellItem.id
          }
        })
      })

      this.x6List.edgeList.map((v, i) => {
        this.graph.addEdge({
          source: { cell: v.sourceCell, port: v.sourcePort },
          target: { cell: v.targetCell, port: v.targetPort },

          label: v.edgeLabel,
        })
      })
    },
    removeedgelist() {
      this.$refs.config.off()
    },
    //提交
    submitList() {
      let data = []
      let date = []
      let arrlist = []
      if (localStorage.getItem('data') || localStorage.getItem('date')) {
        data = JSON.parse(localStorage.getItem('data'))
        date = JSON.parse(localStorage.getItem('date'))
        console.log(date, 'data')
        if (data !== null && data !== []) {
          data.map((v, i) => {
            arrlist.push(v)
          })
        }
        if (date !== null && date !== []) {
          date.map((v, i) => {
            arrlist.push(v)
          })
        }
        console.log(arrlist);
        this.dataArrChildite = arrlist
        if (this.dataArrChildite) {
          this.x6List.cellList.map((v, i) => {
            v.modelId = this.dataArrChildite[0].modelId
          })
          this.x6List.edgeList.map((v, i) => {
            v.modelId = this.dataArrChildite[0].modelId
          })
        }

        let arr = []
        // this.x6List.edgeList.map((v, i) => {
        //   this.dataArrChilditem.map((v1, i1) => {
        //     if (
        //       (v.sourceId == v1.primaryTableid && v.targetId == v1.relationTableid) ||
        //       (v.sourceId == v1.relationTableid && v.targetId == v1.primaryTableid) ||
        //       (v.sourceId == v1.primaryTableid && v.targetId == v1.secondaryTableid) ||
        //       (v.sourceId == v1.secondaryTableid && v.targetId == v1.primaryTableid) ||
        //       (v.sourceId == v1.relationTableid && v.targetId == v1.secondaryTableid) ||
        //       (v.sourceId == v1.secondaryTableid && v.targetId == v1.relationTableid)
        //     ) {
        //       v1.name = v.edgeLabel
        //     }
        //   })
        // })

        this.dataArrChildite.map((v, i) => {
          v.x6List = this.x6List
        })
        let listvar = [...this.dataArrChildite, ...this.metaModelFieldRelationEntities]
        this.type = this.$route.query.type
        if (this.type == 'add') {
          metaModelfieldRelation({
            json: JSON.stringify(listvar),
          }).then((res) => {
            if (res.data.code == 0) {
              this.$message.success(res.data.msg)
              this.$router.push('/metadata/metaModel/core')
            }
            localStorage.removeItem('data')
            localStorage.removeItem('date')
          })
        } else if (this.type == 'edit') {
          let list = []
          let three = []
          let three1 = []

          this.dataArrChildite.map((v, i) => {
            if (v.relationType == '1') {
              list.push({
                edgeId: v.edgeId,
                modelId: v.modelId,
                relationType: v.relationType,
                primarySecondaryConnectedrelationName: v.primarySecondaryConnectedrelationName,
                primaryTableid: v.primaryTableid,
                primaryTablename: v.primaryTablename,
                primaryFieldid: v.primaryFieldid,
                primaryFieldname: v.primaryFieldname,
                secondaryTableid: v.secondaryTableid,
                secondaryTablename: v.secondaryTablename,
                secondaryFieldid: v.secondaryFieldid,
                secondaryFieldname: v.secondaryFieldname,
                x6List: v.x6List,
              })
            } else if (v.relationType == '2') {
              console.log(v)
              if (v.lxtype1 == '111') {
                three.push({
                  lxtype1: '111',
                  edgeId: v.edgeId,
                  modelId: v.modelId,
                  primaryTableid: v.primaryTableid,
                  primaryTablename: v.primaryTablename,
                  primaryFieldid: v.primaryFieldid,
                  primaryFieldname: v.primaryFieldname,
                  relationTableid: v.relationTableid,
                  relationTablename: v.relationTablename,
                  relationFieldid: v.relationFieldid,
                  relationFieldname: v.relationFieldname,
                  relationType: v.relationType,
                  relationPrimaryConnectedrelationName: v.relationPrimaryConnectedrelationName,
                  x6List: v.x6List,
                  starttime: v.starttime,
                  endtime: v.endtime,
                })
              } else if (v.lxtype2 == '222') {
                three1.push({
                  lxtype1: '222',
                  edgeId: v.edgeId,
                  modelId: v.modelId,
                  relationTableid: v.relationTableid,
                  relationTablename: v.relationTablename,
                  relationFieldid: v.relationFieldid,
                  relationFieldname: v.relationFieldname,
                  secondaryTableid: v.secondaryTableid,
                  secondaryTablename: v.secondaryTablename,
                  secondaryFieldid: v.secondaryFieldid,
                  secondaryFieldname: v.secondaryFieldname,
                  relationSecondaryConnectedrelationName: v.relationSecondaryConnectedrelationName,
                  relationType: v.relationType,
                  x6List: this.x6List,
                  starttime: v.starttime,
                  endtime: v.endtime,
                })
              } else {
                three.push({
                  edgeId: v.edgeId,
                  modelId: v.modelId,
                  primaryTableid: v.primaryTableid,
                  primaryTablename: v.primaryTablename,
                  primaryFieldid: v.primaryFieldid,
                  primaryFieldname: v.primaryFieldname,
                  relationTableid: v.relationTableid,
                  relationTablename: v.relationTablename,
                  relationFieldid: v.relationFieldid,
                  relationFieldname: v.relationFieldname,
                  relationType: v.relationType,
                  relationPrimaryConnectedrelationName: v.relationPrimaryConnectedrelationName,
                  x6List: v.x6List,
                  starttime: v.starttime,
                  endtime: v.endtime,
                })
              }
              list = [...three, ...three1]
              console.log(list, 'list');
            }
          })
          let listvar = [...list]
          console.log(listvar, 'listvar');
          metaModelfieldRelation({
            json: JSON.stringify(listvar),
          }).then((res) => {
            if (res.data.code == 0) {
              this.$message.success(res.data.msg)
              this.$router.push('/metadata/metaModel/core')
            }
            localStorage.removeItem('data')
            localStorage.removeItem('date')
          })
        }
      } else {
        this.$message.error('无法提交,至少要配置一个字段关联关系')
      }
    },
    open() {
      this.$prompt('请输入关联关系', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          this.incidenceRelation = value
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入',
          })
        })
    },
    //删除节点
    removeItem(item) {
      console.log(item, '--->999')
      this.x6List.cellList.map((v, i) => {
        if (v.tableId == item.data.tableId) {
          this.x6List.cellList.splice(i, 1)
        }
        this.x6List.edgeList.map((it, index) => {
          if (item.data.tableId == it.sourceId || item.data.tableId == it.targetId) {
            this.x6List.edgeList.splice(index, 1)
          }
        })
      })

      console.log(this.x6List, '删除节点后的this.x6List.cellList')
    },
    //重置画布
    resetList() {
      console.log('resetList')
      this.x6List.cellList = []
      this.x6List.edgeList = []

      this.getG6Echarts()
    },
  },
}
</script>

<style scoped>
.text-right {
  float: right;
}

#container {
  background-image: url('../../../../../../assets/dataRelationBg.png');
  /* 设置背景图像的 URL */
  background-size: cover;
  /* 控制背景图像的尺寸适应容器 */
  /*background-repeat: repeat;*/
  /* 其他背景样式属性，如背景颜色、重复方式等 */
}

/* 自定义节点的样式 */
.el-tree-node__content:hover {
  background-color: #e0e0e0;
  cursor: pointer;
}

/* 自定义工具提示的样式 */
.el-tooltip__popper {
  z-index: 9999;
  /* 确保工具提示显示在顶部 */
}

#treeBox {
  margin-top: 1px;
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
